/**
 * Copyright (c) 2012, http://www.yissugames.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yissugames.blocklife.gamelogic;

import java.util.Random;

import org.lwjgl.util.Rectangle;

import com.yissugames.blocklife.generators.BiomGenerator;

public class Chunk {

	private Block[][] blocks;
	private int offset;
	
	public Chunk(BiomGenerator generator, int last, int offset, Random random)
	{
		blocks = generator.generate(last, offset, random);
		this.offset = offset;
	}
	
	public void render()
	{
		for(int x = 0; x < blocks.length; x++)
			for(int y = 0; y < blocks[0].length; y++)
				if(blocks[x][y] != null)
					blocks[x][y].render(this);
	}
	
	public int getFirstHeight()
	{
		for(int y = 0; y < 256; y++)
			if(blocks[0][y] != null)
				return y;
		
		return 10;
	}
	
	public int getLastHeight()
	{
		for(int y = 0; y < 256; y++)
			if(blocks[31][y] != null)
				return y;
		
		return 10;
	}
	
	public boolean hasBlock(int x, int y)
	{
		try {
			if(blocks[x][y] != null)
				return true;
			return false;
		} catch (Exception e) {
			return false;
		}
	}
	
	public void addBlock(int x, int y, int id)
	{
		if(id == -1)
			return;
		
		blocks[x][y] = Block.Blocks[id].createBlockByThis().setPosition(x + offset, y);
	}
	
	public int destroy(int x, int y)
	{
		//TODO: search for bug that cause an invalid call
		if(x > 31 || y > 255 || x < 0 || y < 0)
			return -1;
		
		int id = blocks[x][y] == null ? -1 : blocks[x][y].getDropId();
		if(blocks[x][y] != null && !blocks[x][y].isDestoryable())
			id = -1;
		else
			blocks[x][y] = null;
		
		return id;
	}
	
	public Rectangle getBounds()
	{
		return new Rectangle(offset * 32, 0, 32 * 32, 256 * 32);
	}

	public int getHeightAt(int x) {
		for(int y = 0; y < 256; y++)
			if(blocks[x][y] != null)
				return y;
		
		return 10;
	}
	
}
